package com.hclc.config;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hclc.config.context.AppContext;
import com.hclc.entity.model.SysUserModel;
import com.hclc.entity.model.contans.ApiConst;
import com.hclc.entity.model.enums.PortTypeEnum;
import com.hclc.entity.model.result.ResultEntity;
import com.hclc.config.util.TokenUtil;
import com.hclc.util.json.JsonUtil;
import lombok.extern.slf4j.Slf4j;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Objects;
import java.util.Optional;

/**
 * @author lixin
 * @version V1.0
 * @ClassName: WebInterceptor
 * @Description: TODO()
 * @date 2019年5月2日 下午7:19:45
 */
@Component
@Slf4j
public class WebInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o)
            throws Exception {
        log.debug("请求url:{}", httpServletRequest.getRequestURL());
        String token = Optional.ofNullable(httpServletRequest.getHeader("token")).orElse("");
        if (!StringUtils.EMPTY.equals(token)) {
            // 后台
            if (TokenUtil.isSpecifyPortType(token, PortTypeEnum.BACKSTAGE)) {
                Subject subject = SecurityUtils.getSubject();
                if (Objects.nonNull(subject) && Objects.nonNull(subject.getPrincipal())) {
                    SysUserModel sysUserModel = (SysUserModel) SecurityUtils.getSubject().getPrincipal();
                    // 初始化系统环境上下文
                    AppContext.initSystemEnvironmentContext(httpServletRequest, httpServletResponse);
                    // 初始化当前登录用户信息
                    AppContext.initCurrentUser(SysUserModel.class.getName(), sysUserModel, token, sysUserModel.getId());
                    return true;
                }
            } else if (TokenUtil.isSpecifyPortType(token, PortTypeEnum.APP)) {
                if (StringUtils.isNotBlank(AppContext.getCurrentUserId()) && !ApiConst.ANONYMOUS_USER_ID.equals(AppContext.getCurrentUserId())) {
                    return true;
                }
            }
        }
        PrintWriter out = httpServletResponse.getWriter();
        out.append(JsonUtil.toJson(ResultEntity.ResultFail(ApiConst.CODE_FAIL_TOKEN, "登录信息失效，请重新登录")));
        out.flush();
        return false;
    }
}
